package workgroup.osaka.DirectLink;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class DirectLinkMainActivity extends Activity implements OnItemSelectedListener, OnItemClickListener, OnClickListener{

	final static String MY_NAME_TEXT = "my_name";
	final static String MY_STATUS_TEXT = "my_status";
	final static String MY_MAC_TEXT = "my_mac";
	final static String MY_GROUP_OWNER_TEXT = "my_group_owner";
	final static String PEER_NAME_TEXT = "peer_name";
	final static String PEER_STATUS_TEXT = "peer_status";
	final static String PEER_MAC_TEXT = "peer_mac";
	final static String PEER_GROUP_OWNER_TEXT = "peer_group_owner";

	final static String SEARCH_BUTTON = "search_b";
	final static String CONNECT_BUTTON = "connect_b";
	final static String SEND_BUTTON = "send_b";

	Spinner stateSpinner;
	String[] states;
	int spinnerItem = 0;

	Button search_b;
	Button connect_b;
	Button send_b;
	Button reset_b;

	TextView my_name;
	TextView my_status;
	TextView my_mac;
	TextView my_group_owner ;

	TextView peer_name;
	TextView peer_status;
	TextView peer_mac;
	TextView peer_group_owner;

	Gallery gallery;
	GalleryHandler GalleryHandler;
	int GalleryFlag = 0;
	ImageView view;
	LinearLayout linearLayout;
	ImageButton[] imgbutton;
	HorizontalScrollView scrView;


	HashMap<Integer, Uri> uriMap = new HashMap<Integer, Uri>(); //URIをMapで管理する
	List<String> imagePath = new ArrayList<String>(); //String List 画像のパス
	Bitmap[] thumbnail; //bitmapデータ(サムネ)

	StatusHandler statusHandler;


	Uri uri;
	Uri g_uri = null;
	DirectLinkConnection DirectLinkConnection = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_direct_link_main);

		stateSpinner = (Spinner)findViewById(R.id.spinner1);
		states = getResources().getStringArray(R.array.protocol);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, states);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		stateSpinner.setAdapter(adapter);
		stateSpinner.setOnItemSelectedListener(this);

		search_b = (Button)findViewById(R.id.search);
		connect_b = (Button)findViewById(R.id.connect);
		send_b = (Button)findViewById(R.id.send);

		my_name = (TextView)findViewById(R.id.MyName);
		my_status = (TextView)findViewById(R.id.MyStatus);
		my_mac = (TextView)findViewById(R.id.MyMacAddress);
		my_group_owner = (TextView)findViewById(R.id.MyGroupOwner);

		peer_name = (TextView)findViewById(R.id.PeerName);
		peer_status = (TextView)findViewById(R.id.PeerStatus);
		peer_mac = (TextView)findViewById(R.id.PeerMacAddress);
		peer_group_owner = (TextView)findViewById(R.id.PeerGroupOwner);

		//linearLayout = (LinearLayout)findViewById(R.id.linearlay);
		scrView = (HorizontalScrollView)findViewById(R.id.scrollView);
		linearLayout = new LinearLayout(this);
		linearLayout.setOrientation(linearLayout.HORIZONTAL);

		getGalleryUri();

		thumbnail = new Bitmap[imagePath.size()];
		imgbutton = new ImageButton[imagePath.size()];
		//gallery = (Gallery)findViewById(R.id.scrollView);
		scrView.addView(linearLayout);
		Log.d("onCreate", "onCreate");
		ResetButton();

	}

	//--------------アクティビティのライフサイクル------------
	public void onPause(){
		super.onPause();
		Log.d("onPause", "onPause");
		//ハンドラを止める
		statusHandler = null;
	}

	public void onResume(){
		super.onResume();
		Log.d("onResume", "onResume");
		if(DirectLinkConnection != null){
			DirectLinkConnection.ResumeConnection();
		}
		//定期処理ハンドラの生成と実行
		statusHandler = new StatusHandler();
		statusHandler.sleep(0);
	}

	public void onStart(){
		super.onStart();
		Log.d("onStart", "onStart");
	}

	public void onStop(){
		super.onStop();
		Log.d("onStop", "onStop");
	}

	public void onRestart(){
		super.onRestart();
		Log.d("onRestart", "onRestart");
	}

	public void onDestroy(){
		super.onDestroy();
		Log.d("onDestroy", "onDestroy" + this.isFinishing());
		if(DirectLinkConnection != null){
			DirectLinkConnection.DestroyConnection();
		}
		gallery = null;
		GalleryHandler = null;

		view.setImageBitmap(null);
		uriMap = null; //URIをMapで管理する
		imagePath = null; //String List 画像のパス
		thumbnail = null; //bitmapデータ(サムネ)
		statusHandler = null;

	}
	//--------------------------------------------------------

	//スピナー変更時の動作
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
		if(spinnerItem != arg0.getSelectedItemPosition()){
			spinnerItem = arg0.getSelectedItemPosition();
			ResetButton();
		}
		Toast.makeText(this, states[spinnerItem], Toast.LENGTH_SHORT).show();
		Log.d("onItemSelected", spinnerItem +  "番目のアイテムが選ばれました");

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0){}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.direct_link_main, menu);
		return true;
	}

	//リセット時(スピナーが変更された時)の動作
	public void ResetButton(){
		search_b.setOnClickListener(new PeerSearchButton());
		connect_b.setEnabled(false);
		send_b.setEnabled(false);

		//切断処理
		if(DirectLinkConnection != null){
			DirectLinkConnection.DisconnectConnection();
			DirectLinkConnection = null;
		}
		Log.d("ResetButton", "ResetButton");

		//テキスト初期化
		ChangeText("",MY_NAME_TEXT);
		ChangeText("",MY_STATUS_TEXT);
		ChangeText("",MY_MAC_TEXT);
		ChangeText("",MY_GROUP_OWNER_TEXT);
		ChangeText("",PEER_NAME_TEXT);
		ChangeText("",PEER_STATUS_TEXT);
		ChangeText("",PEER_MAC_TEXT);
		ChangeText("",PEER_GROUP_OWNER_TEXT);
	}

	//各テキストの表示を変更する
	void ChangeText(String viewStr , String targetText){
		if(MY_NAME_TEXT == targetText){
			//Log.d("ChangeText", "自端末名表示変更：" + viewStr);
			my_name.setText(viewStr);
		}
		if(MY_STATUS_TEXT == targetText){
			//Log.d("ChangeText", "自端末状態表示変更：" + viewStr);
			my_status.setText(viewStr);
		}
		if(MY_MAC_TEXT == targetText){
			//Log.d("ChangeText", "自端末ＭＡＣアドレス表示変更：" + viewStr);
			my_mac.setText(viewStr);
		}
		if(MY_GROUP_OWNER_TEXT == targetText){
			//Log.d("ChangeText", "自端末役割（オーナー or クライアント）表示変更：" + viewStr);
			my_group_owner.setText(viewStr);
		}
		if(PEER_NAME_TEXT == targetText){
			//Log.d("ChangeText", "相手端末名表示変更：" + viewStr);
			peer_name.setText(viewStr);
		}
		if(PEER_STATUS_TEXT == targetText){
			//Log.d("ChangeText", "相手端末状態表示変更：" + viewStr);
			peer_status.setText(viewStr);
		}
		if(PEER_MAC_TEXT == targetText){
			//Log.d("ChangeText", "相手端末ＭＡＣアドレス表示変更：" + viewStr);
			peer_mac.setText(viewStr);
		}
		if(PEER_GROUP_OWNER_TEXT == targetText){
			//Log.d("ChangeText", "相手端末役割（オーナー or クライアント）表示変更：" + viewStr);
			peer_group_owner.setText(viewStr);
		}
	}

	//各ボタンの表示や機能を変更する
	public void ChangeButton(String viewStr, OnClickListener func, String targetButton){
		if(CONNECT_BUTTON == targetButton){
			Log.d("ChangeButton", "「CONNECT_BUTTON設定」 表示名：" + viewStr);
			connect_b.setOnClickListener(func);
			connect_b.setText(viewStr);
		}
		if(SEND_BUTTON == targetButton){
			Log.d("ChangeButton", "「SEND_BUTTON設定」 表示名：" + viewStr);
			send_b.setOnClickListener(func);
			send_b.setText(viewStr);
		}
		if(SEARCH_BUTTON == targetButton){
			Log.d("ChangeButton", "「SEARCH_BUTTON設定」 表示名：" + viewStr);
			search_b.setOnClickListener(func);
			search_b.setText(viewStr);
		}
	}

	//送信する画像を選択するためにギャラリーを開く
	void OpenGallery(){
		int TES = 0;

		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

		intent.setType("image/*");
		Log.d("OpenGallery()", "ギャラリーオープン");
		startActivityForResult(intent,TES);
	}

	//OpenGalleryで選んだ画像のパスを受け取る
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data != null){
			uri = data.getData();
			Log.d("image address", uri.getPath());
			Intent intent = new Intent();
			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.setDataAndType(uri, "image/*");
			this.startActivity(intent);

			Log.d("送信直前","kk");
			Dialog();
		}else{

		}

	}

	//受信した画像を表示する
	void DisplayPicture(String picPath){
		if (picPath != null) {
			Log.d("DisplayPicture", "File copied - " + picPath);
			Intent intent = new Intent();
			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse("file://" + picPath), "image/*");
			this.startActivity(intent);
		}
	}

	//検索ボタンの初期設定（選ばれた接続方法で検索する）
	class PeerSearchButton implements OnClickListener{
		public void onClick(View v){
			Log.d("PeerSearchButton", "検索ボタンクリック（初期設定）");
			if(spinnerItem == 0){
				DirectLinkConnection = new DirectLinkConnection(DirectLinkMainActivity.this);
				DirectLinkConnection.WiFiDirectConnection(g_uri);
				connect_b.setEnabled(true);
				send_b.setEnabled(true);
			}else if(spinnerItem == 1){
				DirectLinkConnection = new DirectLinkConnection(DirectLinkMainActivity.this);
				DirectLinkConnection.BluetoothConnection(g_uri);
				connect_b.setEnabled(true);
				send_b.setEnabled(true);
			}else{
				//無し
			}
		}
	}

	//送信確認ダイアログ表示
	private void Dialog(){
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("確認");
		dialog.setMessage("送信しますか？");
		dialog.setPositiveButton("送信",new DialogInterface.OnClickListener() {

			@Override


			public void onClick(DialogInterface dialog, int which) {
				DirectLinkConnection.SendConnection(uri);
			}
		});
		dialog.setNegativeButton("キャンセル", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		dialog.show();
	}

	/*
	 * 一定時間ごとに端末情報取得するHandler
	 */
	public class StatusHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			//ハンドラがnullになるまで
			if (statusHandler!=null){
				//1秒ごとにsleepメソッド実行
				sleep(1000);
			}
		}

		//スリープメソッド
		public void sleep(long delayMills) {
			//端末情報更新

			if(DirectLinkConnection != null){
				//Log.d("定期更新", "端末情報更新");
				String[] status = new String[8];
				status = DirectLinkConnection.getStatusConnection();
				//自端末情報取得
				ChangeText(status[0] , MY_NAME_TEXT);
				ChangeText(status[1] , MY_STATUS_TEXT);
				ChangeText(status[2] , MY_MAC_TEXT);
				ChangeText(status[3] , MY_GROUP_OWNER_TEXT);
				//相手端末情報更新
				ChangeText(status[4] , PEER_NAME_TEXT);
				ChangeText(status[5] , PEER_STATUS_TEXT);
				ChangeText(status[6] , PEER_MAC_TEXT);
				ChangeText(status[7] , PEER_GROUP_OWNER_TEXT);
			}

			//使用済みメッセージの削除
			removeMessages(0);
			sendMessageDelayed(obtainMessage(0),delayMills);
		}
	}

	//-------------------------------------------------------------------------------------------------------

	//画像一覧表示のために各ディレクトリから画像のUriを取得
	//取得したUriをPathに変換してimagePathにリストとして代入
	public void getGalleryUri(){
		HashMap<Integer, Uri> preUriMap = new HashMap<Integer, Uri>(); //URIをMapで管理する
		List<String> preImagePath = new ArrayList<String>(); //String List 画像のパス
		Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,null);
		cursor.moveToFirst();
		// init for loop
		int fieldIndex;
		Long id;
		int cnt = 0, VolMax = 0,i, j = 0;


		do {
			//カラムIDの取得
			fieldIndex = cursor.getColumnIndex(MediaStore.Images.Media._ID);
			id = cursor.getLong(fieldIndex);

			//IDからURIを取得
			Uri bmpUri = ContentUris.withAppendedId(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
			//uriMap.put(cnt, bmpUri);
			//String path = getPath(this, uriMap.get(cnt));
			//imagePath.add(path);
			//cnt++;
		//} while (cursor.moveToNext());
			preUriMap.put(cnt,  bmpUri);
			String path = getPath(this, preUriMap.get(cnt));
			preImagePath.add(path);

			cnt++;
		} while (cursor.moveToNext());
		VolMax = --cnt;

		for(i = 0; i < VolMax; i++){
			if(preImagePath.get(i).endsWith("jpeg") || preImagePath.get(i).endsWith("jpg")){

				uriMap.put(j, preUriMap.get(i));

				String prepath = getPath(this, uriMap.get(j));

				imagePath.add(prepath);
				j++;
			}
		}

		VolMax = j;

		//VolMax = --cnt;
		Log.d("picture count", Integer.toString(VolMax));
		cnt = 0;
	}

	//UriをPathに変換
	public static String getPath(Context context, Uri uri) {
	    ContentResolver contentResolver = context.getContentResolver();
	    String[] columns = { MediaStore.Images.Media.DATA };
	    Cursor cursor = contentResolver.query(uri, columns, null, null, null);
	    cursor.moveToFirst();
	    String path = cursor.getString(0);
	    cursor.close();
	    return path;
	}

	//public void run(){
	public class getBitMap extends Thread{
		public void run() {
			// TODO 自動生成されたメソッド・スタブ
			int i = 0;
			Canvas canvas;
			//int gallery_height = getResources().getDimensionPixelSize(R.dimen.new_margin);
			for(i = 0; i < imagePath.size(); i++){
				//画像サイズ等の情報取得（inJustDecodeBounds:true）
				BitmapFactory.Options BitMapOptions = new BitmapFactory.Options();
				BitMapOptions.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(imagePath.get(i), BitMapOptions);

				int height = BitMapOptions.outHeight; //元サイズ高さ
				//int scale =  height/50;
				//BitMapOptions.inSampleSize =  height / gallery.getHeight();
				BitMapOptions.inSampleSize = height / scrView.getHeight();
				//BitMapOptions.inSampleSize =  height / gallery_height;
				BitMapOptions.inPreferredConfig = Bitmap.Config.ALPHA_8;


				//画像データ取得（inJustDecodeBounds:false）
				BitMapOptions.inJustDecodeBounds = false;
				thumbnail[i] = BitmapFactory.decodeFile(imagePath.get(i), BitMapOptions);


				//if(!thumbnail[i].isMutable()){
				//	thumbnail[i] = thumbnail[i].copy(Bitmap.Config.ALPHA_8, true);
				//}
				//canvas = new Canvas(thumbnail[i]);

				//thumbnail[i] = makeCanvas(i);

				int h = thumbnail[i].getHeight();

				//float floatScale = (float)gallery.getHeight()/h;
				float floatScale = (float)scrView.getHeight()/h;

				Matrix matrix = new Matrix();
				matrix.postScale(floatScale, floatScale);
				if(matrix != null){
					thumbnail[i] = Bitmap.createBitmap(thumbnail[i], 0, 0, thumbnail[i].getWidth(), h, matrix, true);
				}

			}
			Log.d("getBitMap",Integer.toString(i));
			GalleryHandler = null;
			GalleryFlag = 1;
			runOnUiThread(new Runnable() {
				public void run() {
					Log.d("getBitMap", "call DrowPicture");
					DrowPicture();
				}
			});
		}
	}

	public Bitmap makeCanvas(int i){
		Bitmap checkOn = BitmapFactory.decodeResource(getResources(), drawable.checkbox_on_background);
		Bitmap checkOff = BitmapFactory.decodeResource(getResources(), drawable.checkbox_off_background);
		int h = thumbnail[i].getHeight();
		int w = thumbnail[i].getWidth();
		//Bitmap preBitMap = Bitmap.createBitmap(w, h, Bitmap.Config.ALPHA_8);
		Bitmap preBitMap = thumbnail[i];
		if(!preBitMap.isMutable()){
			preBitMap = preBitMap.copy(Bitmap.Config.ALPHA_8, true);
		}
		Canvas canvas = new Canvas();
		canvas.setBitmap(thumbnail[i]);
		//Log.d("height width", "" + h + " " + w);
		//canvas.drawBitmap(thumbnail[i], 0, 0, (Paint)null);
		//canvas.drawBitmap(checkOn, 3, 3, (Paint)null);

		//ImageView imageView;
		//imageView.setImageBitmap(preBitMap);

		//BitmapDrawable bd = (BitmapDrawable)imageView.getDrawable();
		//Bitmap bmp = bd.getBitmap();


		return preBitMap;
	}

	//Galleryを表示するためのアダプタ
	public class GalleryAdapter extends BaseAdapter{

		//画像の数を返す
		@Override
		public int getCount() {
			return imagePath.size();
		}

		//今回は使用しない
		@Override
		public Object getItem(int arg0) {
			return null;
		}

		//今回は使用しない
		@Override
		public long getItemId(int position) {
			return 0;
		}

		//Galleryに画像表示
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if(convertView == null){
				view = new ImageView(DirectLinkMainActivity.this);
				//checkbox = new ImageView(DirectLinkMainActivity.this);
				//checkbox.setImageResource(drawable.ic_btn_speak_now);
				view.setImageBitmap(thumbnail[position]);
			}else{
				view = (ImageView)convertView;
			}
			return view;
		}
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		getBitMap mt = new getBitMap();
		Thread thread = new Thread(mt);

		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);

		// Viewのサイズを取得
		//Log.d("onWindowFocusChanged", "Gallery width=" + gallery.getWidth() + ", height=" + gallery.getHeight());
		if(GalleryFlag == 0){
			thread.start();

			//DrowGallery();

			//GalleryHandler = new GalleryHandler();
			//GalleryHandler.sleep(0);
		}
	}

	public class GalleryHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			//ハンドラがnullになるまで
			if (GalleryHandler!=null){
				//1秒ごとにsleepメソッド実行
				sleep(1000);
			}
		}
		//スリープメソッド
		public void sleep(long delayMills) {
			//DrowGallery();
			//DrowPicture(); ////////////////////error
			//使用済みメッセージの削除
			removeMessages(0);
			sendMessageDelayed(obtainMessage(0),delayMills);
		}
	}

	//ギャラリーに画像を表示する
	public void DrowGallery(){
		gallery.setSpacing(10);
		gallery.setAdapter(new GalleryAdapter()); //ギャラリーアダプタ呼び出し
		gallery.setOnItemClickListener(DirectLinkMainActivity.this);
	}

	public void DrowPicture(){
		int i;

		for(i = 0; i < imagePath.size(); i++){
			if(thumbnail[i] != null){
			Log.d("Drow Picture1",imagePath.get(i));
			Log.d("Drow Picture2","" + uriMap.get(i));
			imgbutton[i] = new ImageButton(DirectLinkMainActivity.this); ///////////////////error
			imgbutton[i].setImageBitmap(thumbnail[i]);
			imgbutton[i].setPadding(5, 0, 5, 0);
			imgbutton[i].setOnClickListener(new PushImage(i));

			linearLayout.addView(imgbutton[i]);
			//setContentView(linearLayout);
			}
		}
		//scrView.addView(linearLayout);
	}

	//ギャラリーの画像が選択された時の動作
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO 自動生成されたメソッド・スタブ
		if(arg0 == gallery){
			Log.d("ItemClick path",imagePath.get(arg2));
			Log.d("ItemClick uri", "" + uriMap.get(arg2));
			g_uri = uriMap.get(arg2);
			Toast.makeText(this, "画像を選択しました", Toast.LENGTH_SHORT).show();
			if(DirectLinkConnection != null){
				DirectLinkConnection.setUriConnection(g_uri);
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO 自動生成されたメソッド・スタブ


	}
	class PushImage implements OnClickListener{
		int imageNum;
		PushImage(int i){
			imageNum = i;
		}

		@Override
		public void onClick(View arg0) {
			// TODO 自動生成されたメソッド・スタブ
			Log.d("Push Image",imagePath.get(imageNum));
			Log.d("Push Image", "" + uriMap.get(imageNum));


			g_uri = uriMap.get(imageNum);
			Toast.makeText(DirectLinkMainActivity.this, "画像を選択しました", Toast.LENGTH_SHORT).show();
			if(DirectLinkConnection != null){
				DirectLinkConnection.setUriConnection(g_uri);
			}

		}

	}
}
